package com.app.config;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import com.app.common.Api;
import com.app.config.annotation.FrontName;
import org.springframework.boot.context.properties.bind.validation.BindValidationException;
import org.springframework.boot.context.properties.bind.validation.ValidationErrors;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.Field;
import java.util.StringJoiner;

@RestControllerAdvice
public class GlobalExceptionConfig {

    @ExceptionHandler(BindException.class)
    public Api bindException(BindException e) {
        Class<?> targetClazz = e.getTarget().getClass();
        StringJoiner errInfo = new StringJoiner("\r\n");
        e.getFieldErrors().forEach(err -> {
            Field field = ReflectUtil.getField(targetClazz, err.getField());
            if (AnnotationUtil.hasAnnotation(field, FrontName.class)) {
                errInfo.add(AnnotationUtil.getAnnotationValue(field, FrontName.class) + err.getDefaultMessage());
            } else {
                errInfo.add(err.getField() + ":" + err.getDefaultMessage());
            }
        });
        return Api.fail(errInfo.toString());
    }

    @ExceptionHandler(Exception.class)
    public Api exceptionHandler(Exception e) {
        return Api.fail(e.getMessage());
    }
}
